#ifndef EXCEPTION_HPP
#define EXCEPTION_HPP

/**
 * \file
 * \ingroup exception
 * \brief SABORT*, SASSERT*, SFATAL* macro definitions
 */

/**
 * \ingroup core
 * \defgroup exception Exception
 */

#include <iostream>
#include <exception>
#include <cstdlib>

#include "core/fatal-impl.hpp"
#include "core/log-enabled.hpp" // SLOG_APPEND_*

/**
 * \ingroup exception
 * \defgroup fatal Fatal Error Handlers
 *
 * \brief Functions to help clean up when a fatal error
 * is encountered.
 *
 * The functions in this group are used to perform
 * limited clean up, like flushing active streams, when
 * fatal errors are encountered (through assertion fail,
 * calls to SABORT_* or calls to SFATAL_ERROR).
 *
 * Currently, other than flushing active ostreams, these
 * functions does not interfere with outside memory.  There
 * is still a residual risk that invalid ostream
 * pointers may be present, and may corrupt the memory
 * on the attempt to execute the flush() function.
 */

/**
 * \ingroup fatal
 * \brief Fatal error reporting with no message, implementation.
 *
 * When this macro is hit at runtime the error details will
 * printed to \c stderr, including the file name and line number.
 * Optionally, if \c fatal is true, the macro
 * will invoke \c std::terminate().  If \c fatal is false,
 * the invoking function should return an error code to its caller,
 * which is expected to call NS_FATAL_ERROR to cause termination.
 *
 * \param [in] fatal Call \c std::terminate() if true.
 *
 * This macro is enabled unconditionally in all builds,
 * including debug and optimized builds.
 */
#define SFATAL_ERROR_IMPL_NO_MSG(fatal)                                         \
    do                                                                          \
    {                                                                           \
        SLOG_APPEND_TIME_PREFIX_IMPL;                                           \
        SLOG_APPEND_NODE_PREFIX_IMPL;                                           \
        std::cerr << "file=" << __FILE__ << ", line=" << __LINE__ << std::endl; \
        cas::FatalImpl::FlushStreams();                                         \
        if (fatal)                                                              \
            std::terminate();                                                   \
    } while (false)

/**
 * \ingroup fatal
 * \brief Fatal error reporting with a message, implementation.
 *
 * When this macro is hit at runtime the error details will
 * printed to \c stderr, including the message, file name and line number.
 * Optionally, if \c fatal is true, the macro
 * will invoke \c std::terminate().  If \c fatal is false,
 * the invoking function should return an error code to its caller,
 * which is expected to call NS_FATAL_ERROR to cause termination.
 *
 * \param [in] msg The error message to print, if not empty.
 * \param [in] fatal Call \c std::terminate() if true.
 *
 * This macro is enabled unconditionally in all builds,
 * including debug and optimized builds.
 */
#define SFATAL_ERROR_IMPL(msg, fatal)           \
    do                                          \
    {                                           \
        std::cerr << "msg=\"" << msg << "\", "; \
        SFATAL_ERROR_IMPL_NO_MSG(fatal);        \
    } while (false)

/**
 * \ingroup fatal
 * \brief Report a fatal error and terminate.
 *
 * When this macro is hit at runtime, details of filename
 * and line number are printed to \c stderr, and the program
 * is halted by calling \c std::terminate(). This will
 * trigger any clean up code registered by
 * \c std::set_terminate (NS3 default is a stream-flushing
 * code), but may be overridden.
 *
 * This macro is enabled unconditionally in all builds,
 * including debug and optimized builds.
 */
#define SFATAL_ERROR_NO_MSG() SFATAL_ERROR_IMPL_NO_MSG(true)

/**
 * \ingroup fatal
 *
 * \brief Report a fatal error, deferring termination.
 *
 * When this macro is hit at runtime, details of filename
 * and line number are printed to \c stderr, however the program
 * is _not_ halted.  It is expected that the function using this
 * macro will return an error code, and its caller will
 * invoke NS_FATAL_ERROR(msg) triggering std::terminate().
 *
 * This macro is enabled unconditionally in all builds,
 * including debug and optimized builds.
 */
#define SFATAL_ERROR_NO_MSG_CONT() SFATAL_ERROR_IMPL_NO_MSG(false)

/**
 * \ingroup fatal
 *
 * \brief Report a fatal error with a message and terminate.
 *
 * \param [in] msg message to output when this macro is hit.
 *
 * When this macro is hit at runtime, the user-specified
 * error message are printed to \c stderr, followed by a call
 * to the SFATAL_ERROR_NO_MSG() macro which prints the
 * details of filename and line number to \c stderr. The
 * program will be halted by calling \c std::terminate(),
 * triggering any clean up code registered by
 * \c std::set_terminate (CAS default is a stream-flushing
 * code, but may be overridden).
 *
 * This macro is enabled unconditionally in all builds,
 * including debug and optimized builds.
 */
#define SFATAL_ERROR(msg) SFATAL_ERROR_IMPL(msg, true)

/**
 * \ingroup fatal
 * \brief Report a fatal error with a message, deferring termination.
 *
 * When this macro is hit at runtime, details of filename
 * and line number are printed to \c stderr, however the program
 * is _not_ halted.  It is expected that the function using this
 * macro will return an error code, and its caller will
 * invoke SFATAL_ERROR(msg) triggering \c std::terminate().
 *
 * This macro is enabled unconditionally in all builds,
 * including debug and optimized builds.
 */
#define SFATAL_ERROR_CONT(msg) SFATAL_ERROR_IMPL(msg, false)

/**
 * \ingroup exception
 * \defgroup abort Abortions
 * \c SABORT* macro definitions.
 */

/**
 * \ingroup abort
 * \brief Unconditional abnormal program termination with a message.
 * \param [in] msg The message to output when this macro is hit.
 *
 * This macro is essentially equivalent to SFATAL_ERROR,
 * except it prepends the error message with the string
 * "aborted. ". When this macro is hit at runtime, the
 * program will be halted using \c std::terminate, which
 * triggers clean up code registered by \c std::set_terminate.
 *
 * This macro is enabled unconditionally in all builds,
 * including debug and optimized builds.
 *
 * \see SFATAL_ERROR
 */
#define SABORT_MSG(msg)           \
    do                            \
    {                             \
        std::cerr << "aborted. "; \
        SFATAL_ERROR(msg);        \
    } while (false)

/**
 * \ingroup abort
 * \brief Abnormal program termination if a condition is \c true.
 * \param [in] cond The condition to be evaluated.
 *
 * This is similar to \c SASSERT(!(cond)), except this check
 * is enabled in all builds. If \c cond is evaluated to \c true,
 * the expression for \c cond is printed to \c stderr,
 * followed by a call to the SFATAL_ERROR_NO_MSG() macro
 * which prints the details of filename and line number to
 * \c stderr. The program will be halted by calling
 * \c std::terminate(), triggering any clean up code registered
 * by \c std::set_terminate.  CAS default is a stream-flushing
 * code, but may be overridden.
 *
 * This macro is enabled unconditionally in all builds,
 * including debug and optimized builds.
 */
#define SABORT_IF(cond)                                       \
    do                                                        \
    {                                                         \
        if (unlikely(cond))                                   \
        {                                                     \
            std::cerr << "aborted. cond=\"" << #cond << ", "; \
            SFATAL_ERROR_NO_MSG();                            \
        }                                                     \
    } while (false)

/**
 * \ingroup abort
 * \brief Abnormal program termination if a condition is \c true,
 * with a message.
 * \param [in] cond The condition to be evaluated.
 * \param [in] msg The message to output when cond is \c true.
 *
 * This is similar to SASSERT_MSG(!(cond)), except this
 * check is enabled in all builds. If \c cond is evaluated to
 * \c true, the expression for \c cond is printed to
 * \c stderr, followed by a call to the SFATAL_ERROR() macro
 * which prints the user-specified error message, and details
 * of filename and line number to \c stderr. The program will
 * be halted by calling \c std::terminate(), triggering any
 * clean up code registered by \c std::set_terminate. The ns-3
 * default is a stream-flushing code, but may be overridden.
 *
 * This macro is enabled unconditionally in all builds,
 * including debug and optimized builds.
 */
#define SABORT_MSG_IF(cond, msg)                                \
    do                                                          \
    {                                                           \
        if (unlikely(cond))                                     \
        {                                                       \
            std::cerr << "aborted. cond=\"" << #cond << "\", "; \
            SFATAL_ERROR(msg);                                \
        }                                                       \
    } while (false)

/**
 * \ingroup abort
 * \brief Abnormal program termination if a condition is \c false.
 * \param [in] cond The condition to be evaluated.
 *
 * This is an alias for SABORT_IF(!(cond))
 *
 * \see SABORT_IF
 */
#define SABORT_UNLESS(cond) SABORT_IF(!(cond))

/**
 * \ingroup abort
 * \brief Abnormal program termination if a condition is \c false, with a message.
 * \param [in] cond The condition to be evaluated.
 * \param [in] msg The message to output if cond is false.
 *
 * This is an alias for NS_ABORT_MSG_IF(!(cond))
 *
 * \see SABORT_MSG_IF
 */
#define SABORT_MSG_UNLESS(cond, msg) SABORT_MSG_IF(!(cond), msg)

/**
 * \ingroup exception
 * \defgroup assert Assertions
 *
 * \brief Assert functions and macros
 *
 * The assert macros are used to verify
 * at runtime that a certain condition is true. If it is
 * not true, the program halts. These checks are built
 * into the program only in debugging builds. They are
 * removed in optimized builds.
 *
 * These macro are intended to check certain conditions
 * to be true. Do not put code that also have side effects
 * that your program relies on (eg. code that advances
 * an iterator and return false at end of file) because
 * the code will not be executed on release builds!!
 *
 * If assertion-style checks are required for release
 * builds, use NS_ABORT_UNLESS and NS_ABORT_MSG_UNLESS.
 */

#ifdef SASSERT_ENABLE
/**
 * \ingroup assert
 * \param [in] condition Condition to verify.
 *
 * At runtime, in debugging builds, if this condition is not
 * true, the program prints the source file, line number and
 * unverified condition and halts by calling std::terminate
 */
#define SASSERT(condition)                        \
    do                                            \
    {                                             \
        if (!likely(condition))                 \
        {                                         \
            std::cerr << "assert failed. cond=\"" \
                      << #condition << "\", ";    \
            SFATAL_ERROR_NO_MSG();                \
        }                                         \
    } while (false)

/**
 * \ingroup assert
 * \param [in] condition Condition to verify.
 * \param [in] message Message to output
 *
 * At runtime, in debugging builds, if this condition is not
 * true, the program prints the message to output and
 * halts by calling std::terminate.
 */
#define SASSERT_MSG(condition, message)                                    \
    do                                                                     \
    {                                                                      \
        if (!likely(condition))                                          \
        {                                                                  \
            std::cerr << "assert failed. cond=\"" << #condition << "\", "; \
            SFATAL_ERROR(message);                                         \
        }                                                                  \
    } while (false)

#else /* SASSERT_ENABLE */

#define SASSERT(condition)       \
    do                           \
    {                            \
        (void)sizeof(condition); \
    } while (false)

#define SASSERT_MSG(condition, message) \
    do                                  \
    {                                   \
        (void)sizeof(condition);        \
    } while (false)

#endif /* !SASSERT_ENABLE */

#endif /* EXCEPTION_HPP */
